/*
 *  Copyright 2009 Johan Maasing.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package com.google.code.pj2r.resources.mocks.request;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import javax.servlet.ServletInputStream;

/**
 * Moch request that holds a body.
 * @author Johan Maasing
 */
public class MockBodyHttpServletRequest extends MockHeadersHttpServletRequest {

	private String contentType = "application/x-www-form-urlencoded";
	private String charset = "ISO-8859-1";
	private String body;

	public MockBodyHttpServletRequest(String pathInfo, String method, String body) {
		super(pathInfo, method);
		this.body = body;
	}

	public String getCharacterEncoding() {
		return charset;
	}

	public String getContentType() {
		return contentType;
	}

	/**
	 * For testing
	 */
	public void setContentType(final String newContentType) {
		this.contentType = newContentType;
	}

	public void setCharacterEncoding(String encoding) {
		this.charset = encoding;
	}

	public ServletInputStream getInputStream() throws IOException {
		return new MockServletInputStream();
	}

	class MockServletInputStream extends ServletInputStream {

		final ByteArrayInputStream ins;

		public MockServletInputStream() throws UnsupportedEncodingException {
			ins = new ByteArrayInputStream(body.getBytes(charset));
		}

		public int read() throws IOException {
			return ins.read();
		}
	}
}
